package com.oig.sys.msg.service.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.common.exception.BadRequestException;
import com.oig.sys.msg.dao.ITbMqConfigDao;
import com.oig.sys.msg.dao.ITbMqMsgDao;
import com.oig.sys.msg.dto.MqMsgDto;
import com.oig.sys.msg.entity.TbMqConfig;
import com.oig.sys.msg.entity.TbMqMsg;
import com.oig.sys.msg.service.ITbMqMsgHisService;
import com.oig.sys.msg.service.ITbMqMsgService;
import com.oig.sys.msg.vo.MqMsgVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author wuxl
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TbMqMsgServiceImpl implements ITbMqMsgService {

	private final ITbMqMsgDao tbMqMsgDao;
	private final ITbMqConfigDao mqConfigDao;
	private final ITbMqMsgHisService mqMsgHisService;


	/**
	 * 要检查配置，配置不正常，抛异常
	 */
	@Transactional
	@Override
	public MqMsgVo addMqMsg(MqMsgDto mqMsgDto){
		TbMqConfig config = this.mqConfigDao.getOkMqConfig(mqMsgDto.getRelationType()) ;
		if (config==null){
			throw new BadRequestException("配置不存在") ;
		}
		TbMqMsg mqMsg = new TbMqMsg();
		BeanUtils.copyProperties(mqMsgDto, mqMsg, "id");
		mqMsg.setErrorFlag(CommonEnum.FlagEnum.FALSE_FLAG.getCode());
		mqMsg.setSendFlag(null);
		mqMsg.setSendNum(0);
		mqMsg.setCreateTime(new Date());
		this.tbMqMsgDao.save(mqMsg) ;
		MqMsgVo msgVo = new MqMsgVo();
		BeanUtils.copyProperties(mqMsg, msgVo);
		return msgVo ;
	}

	@Override
	public TbMqMsg getMqMsg(Integer id) {
		return this.tbMqMsgDao.getMqMsgById(id);
	}

	@Override
	public List<TbMqMsg> findAllUnReadyMsg() {
		return this.tbMqMsgDao.findUnReadyMsg();
	}

	@Override
	public List<TbMqMsg> findAllUnSendMqMsg() {
		return this.tbMqMsgDao.findUnSendMsg();
	}

	@Transactional
	@Override
	public void updateMsgError(TbMqMsg mqMsg) {
		mqMsg.setErrorFlag(CommonEnum.FlagEnum.TRUE_FLAG.getCode());
		this.tbMqMsgDao.save(mqMsg);
	}

	@Transactional
	@Override
	public void updateMsgReady(TbMqMsg mqMsg) {
		mqMsg.setSendFlag(CommonEnum.FlagEnum.FALSE_FLAG.getCode());
		this.tbMqMsgDao.save(mqMsg);
	}



	@Transactional
	@Override
	public void moveMsgToHis(TbMqMsg mqMsg) {
		this.mqMsgHisService.addMqMsgHis(mqMsg);
		this.tbMqMsgDao.delete(mqMsg);
	}
}
